package com.bdqn.t308.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.t308.exception.LoginException;
import com.bdqn.t308.pojo.SysUser;
import com.bdqn.t308.service.SysUserService;
import javafx.fxml.LoadException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


@Controller
public class SysUserController {
    Logger logger = Logger.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;


    /**
     * 用户登录
     * @param sysUser：页面请求的数据封装到sysUser实体类中
     * @return
     */
    @RequestMapping("/user/login")
    public String login(SysUser sysUser, HttpServletRequest request) throws LoginException {

        //调用登录方法
        SysUser user = sysUserService.login(sysUser);

        if(user == null){   //用户不存在
            throw new LoginException("用户名不存在！");
        }

        //判断用户名密码是否与输入的密码一致
        if(!user.getPassword().equals(sysUser.getPassword())){
            throw new LoginException("密码错误！");
        }

        //将用户信息存入session
        request.getSession().setAttribute("userSession",user);
        //登录成功
        return "redirect:/toMain";
    }

    /**
     * 去到应用主页
     * @param session
     * @return
     */
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        //进入判断用户是否登录
        if(session.getAttribute("userSession") == null){
            return "redirect:/login";
        }
        return "frame";
    }

    /**
     * 用户退出
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //清空session信息
        session.invalidate();
        return "redirect:/login";
    }

    @RequestMapping("/user/toAdd")
    public String toAdd(){

        return "sysUser/add";
    }

    @RequestMapping("/user/add")
    public String addUser(SysUser sysUser,HttpServletRequest request,
                          @RequestParam(value = "idPic",required = false)MultipartFile file){
        String idPicPath = null;
        //判断上传文件是否为空
        if(!file.isEmpty()){
            //定义上传文件的存储路径，上传的文件全部保存在这个目录下
            String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
            logger.info("上传文件路径："+path);
            //获取源文件名
            String originalFile = file.getOriginalFilename();
            logger.info("源文件名："+originalFile);
            //获取原文件名后缀、
            String prefix = FilenameUtils.getExtension(originalFile);
            logger.info("原文件名后缀："+prefix);
            //定义文件上传大小，超过该大小提示不可上传
            //5000000byte/1024 5000K/1024 = 5M
            int filesSize = 5000000;
            //判断文件大小
            if(file.getSize()>filesSize){
                request.setAttribute("uploadFileError","文件大小不得超过5M");
                return "sysUser/add";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
                //判断文件名后缀，因为是图片，所以必须是以上几种后缀格式
                //为了保证文件不重复，重新生成新的文件名
                //此处生成规则：系统时间戳+随机数+_Person.+后缀名
                String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal."+prefix;
                logger.info("新生成的文件名为："+fileName);
                //创建文件对象
                File targetFile = new File(path);
                //如果文件路径不存在，则创建目录
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    file.transferTo(new File(targetFile,fileName));
                } catch(Exception ex){
                    ex.printStackTrace();
                    request.setAttribute("uploadFileError","上传失败！");
                    return "sysUser/add";
                }
                //保存文件所在路径，便于后续保存在数据库中
                idPicPath = File.separator+"static"+File.separator+"uploadFiles"+File.separator+fileName;

            }else{
                request.setAttribute("uploadFileError","上传图片格式不正确！");
                return "sysUser/add";
            }
        }
        //对上传文件的数据进行处理之前，先判断是否为空，若为空，则跳过上传文件的处理
        //此处是继续添加除图片之外的其他数据字段
        sysUser.setIdPicPath(idPicPath);
        //新增成功跳转到用户列表
        if(sysUserService.addUser(sysUser)>=1){
            return "redirect:/toMain";
        }
        return "user/addUser";

    }


    /**
     * 检查用户名是否重复
     * @param request
     * @param response
     */
    @RequestMapping(value = "/user/checkUserName",produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public Object checkUserName(Map map, HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");*/
        //根据页面输入的用户名，查询数据库，校验用户名是否已存在
        System.out.println("调用数据库查询用户名是否存在！！");
        //map.put("exists",1);
        //调用JSON.toJSONString(Object ojb);
        //return JSON.toJSONString(map);

        //返回JavaBean对象
        SysUser sysUser = new SysUser("admin","123456");
        return JSON.toJSONString(sysUser);
        /*PrintWriter out = response.getWriter();
        out.print(true);
        out.flush();
        out.close();*/
    }





}
